import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

// 引入组件
import Userlist from '../views/Userlist.vue'
import Login from '../components/Login.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      redirect: '/userlist',
      name: 'Home',
      component: Home,
      children: [
        {
          path: 'userlist',
          component: Userlist

        }
      ]
    },
    { path: '/login', component: Login }
  ]
})

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/' || to.path === '/userlist') {
    const token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
  next()
})

export default router
